<template>
    <Modal
            scrollable
            v-model="modal"
            @on-cancel="onCancel"
            :title="$t('page.product.add_package')"
            class-name="vertical-center-modal"
            width="950"
    >
        <Form
                ref="formDynamic"
                :model="formDynamic"
                :rules="rules"
                class="attrFrom"
                :label-width="labelWidth"
                :label-position="labelPosition"
                @submit.native.prevent
        >
            <Row :gutter="24">
              <Col span="24" class="mb15">
                <FormItem :label="$t('page.product.number')+'：'" prop="no">
                  <Input
                      :maxlength="30"
                      v-model="formDynamic.no"
                  />
                </FormItem>
              </Col>
              <Col span="6" class="mb15">
                <FormItem :label="$t('page.product.length')+'(cm)：'" prop="length">
                  <Input
                      type="number"
                      :maxlength="20"
                      v-model="formDynamic.length"
                  />
                </FormItem>
              </Col>
              <Col span="6" class="mb15">
                <FormItem :label="$t('page.product.width')+'(cm)：'" prop="width">
                  <Input
                      type="number"
                      :maxlength="20"
                      v-model="formDynamic.width"
                  />
                </FormItem>
              </Col>
              <Col span="6" class="mb15">
                <FormItem :label="$t('page.product.height')+'(cm)：'" prop="height">
                  <Input
                      type="number"
                      :maxlength="20"
                      v-model="formDynamic.height"
                  />
                </FormItem>
              </Col>
              <Col span="6" class="mb15">
                <FormItem :label="$t('page.product.weight')+'(KG)：'" prop="weight">
                  <Input
                      type="number"
                      :maxlength="20"
                      v-model="formDynamic.weight"
                  />
                </FormItem>
              </Col>
              <Col span="8" class="mb15">
                <FormItem :label="$t('page.product.warning_quantity')+'：'" prop="lsa_quantity">
                  <Input
                      type="number"
                      :maxlength="20"
                      v-model="formDynamic.lsa_quantity"
                  />
                </FormItem>
              </Col>


            </Row>
           
        </Form>
        <div slot="footer">
            <Button @click="cancle">{{$t('page.product.cancel')}}</Button>
            <Button
                    type="primary"
                    :loading="modal_loading"
                    @click="handleSubmit('formDynamic')"
            >{{$t('page.product.save')}}</Button>
        </div>
    </Modal>
</template>

<script>
    import { mapState } from "vuex";
    import { ruleAddApi, ruleInfoApi,packageAddApi,packageDetailApi } from "@/api/product";
    export default {
        name: "addAttr",
        data() {
            return {
                spinShow: false,
                modal_loading: false,
                grid: {
                    xl: 3,
                    lg: 3,
                    md: 12,
                    sm: 24,
                    xs: 24,
                },
                modal: false,
                index: 1,
                rules: {
                    rule_name: [
                        { required: true, message: "请输入分类名称", trigger: "blur" },
                    ],
                },
                formDynamic: {
                  id:0,
                  no:"",
                  length: 0,
                  width: 0,
                  height: 0,
                  weight: 0,
                  spec: [],
                  lsa_quantity: 0,
                },
                attrsName: "",
                attrsVal: "",
                formDynamicNameData: [],
                isBtn: false,
                formDynamicName: [],
                results: [],
                result: [],
                ids: 0,
                title: "添加包裹",
            };
        },
        computed: {
            ...mapState("admin/layout", ["isMobile"]),
            labelWidth() {
                return this.isMobile ? undefined : 150;
            },
            labelPosition() {
                return this.isMobile ? "top" : "right";
            },
        },
        methods: {
			parseFloatValue(value) {
			      // 处理空值
			      if (value === null || value === undefined || value === "") return null;
			      
			      // 处理字符串类型
			      if (typeof value === "string") {
			        // 移除逗号等非数字字符（保留小数点和负号）
			        const cleaned = value.replace(/[^\d.-]/g, '');
			        if (cleaned === "" || cleaned === "." || cleaned === "-") return null;
			        
			        const num = parseFloat(cleaned);
			        return isNaN(num) ? null : num;
			      }
			      
			      // 处理数字类型
			      if (typeof value === "number") {
			        return value;
			      }
			      
			      return null;
			    },
            onCancel() {
                this.clear();
            },
            // 添加按钮
            addBtn() {
                if(this.formDynamic.rule_name.trim() == ''){
                    return this.$Message.error('请输入分类名称');
                }
                this.isBtn = true;
            },
            // 详情
            getIofo(row) {
                this.spinShow = true;
                this.ids = row.id;
                this.title = "编辑包裹";
                packageDetailApi(row.id)
                    .then((res) => {
                        this.formDynamic = res.data.info;
                        this.spinShow = false;
                    })
                    .catch((res) => {
                        this.spinShow = false;
                        this.$Message.error(res.msg);
                    });
            },
            // 提交
            handleSubmit(name) {
                if (this.formDynamic.no.length === 0) {
                    return this.$Message.warning($t('page.product.add_package_number_msg'));
                }
				if (this.formDynamic.length.length === 0 || this.formDynamic.length <= 0) {
				    return this.$Message.warning($t('page.product.add_package_length_msg'));
				}
				if (this.formDynamic.width.length === 0 || this.formDynamic.width <= 0) {
				    return this.$Message.warning($t('page.product.add_package_width_msg'));
				}
				if (this.formDynamic.height.length === 0 || this.formDynamic.height <= 0) {
				    return this.$Message.warning($t('page.product.add_package_height_msg'));
				}
				if (this.formDynamic.weight.length === 0 || this.formDynamic.weight <= 0) {
				    return this.$Message.warning($t('page.product.add_package_weight_msg'));
				}
				if(this.formDynamic.lsa_quantity <= 0){
					return this.$Message.warning($t('page.product.add_package_quantity_msg'));
				}
                this.modal_loading = true;
				// 验证并转换值
				const h = this.parseFloatValue(this.formDynamic.height);
				const l = this.parseFloatValue(this.formDynamic.length);
				const we = this.parseFloatValue(this.formDynamic.weight);
				const w = this.parseFloatValue(this.formDynamic.width);
				const lsa_quantity = this.parseFloatValue(this.formDynamic.lsa_quantity);
				const params = {
					no:this.formDynamic.no,
					height:h,
					length:l,
					weight:we,
					width:w,
					lsa_quantity:lsa_quantity,
				};
                setTimeout(() => {
                    packageAddApi(params, this.ids)
                        .then((res) => {
                            this.$Message.success(res.msg);
							//	请求接口
                            setTimeout(() => {
                                this.modal = false;
                                this.modal_loading = false;
                            }, 500);
                            setTimeout(() => {
                                this.$emit("getList");
                                this.clear();
                            }, 600);
                        })
                        .catch((res) => {
                            this.modal_loading = false;
                            this.$Message.error(res.msg);
                        });
                }, 1200);
            },
            clear() {
                this.$refs["formDynamic"].resetFields();
                this.formDynamic.spec = [];
                this.isBtn = false;
                this.ids = 0;
                this.title = "添加包裹";
                this.attrsName = "";
                this.attrsVal = "";
            },
            // 取消
            offAttrName() {
                this.isBtn = false;
            },
            cancle() {
                this.modal = false;
                this.clear()
            },
            // 删除
            handleRemove(index) {
                this.formDynamic.spec.splice(index, 1);
            },
            // 删除属性
            handleRemove2(item, index) {
                item.splice(index, 1);
            },
            // 添加规则名称
            createAttrName() {
                if (this.attrsName && this.attrsVal) {
                    let data = {
                        value: this.attrsName,
                        detail: [this.attrsVal],
                    };
                    this.formDynamic.spec.push(data);
                    var hash = {};
                    this.formDynamic.spec = this.formDynamic.spec.reduce(function(
                        item,
                        next
                        ) {
                            /* eslint-disable */
                            hash[next.value] ? "" : (hash[next.value] = true && item.push(next));
                            return item;
                        },
                        []);
                    this.attrsName = "";
                    this.attrsVal = "";
                    this.isBtn = false;
                } else {
                    this.$Message.warning("请添加规格名称或规格值");
                }
            },
            // 添加属性
            createAttr(num, idx) {
                if (num) {
                    this.formDynamic.spec[idx].detail.push(num);
                    var hash = {};
                    this.formDynamic.spec[idx].detail = this.formDynamic.spec[
                        idx
                        ].detail.reduce(function(item, next) {
                        /* eslint-disable */
                        hash[next] ? "" : (hash[next] = true && item.push(next));
                        return item;
                    }, []);
                } else {
                    this.$Message.warning("请添加属性");
                }
            },
        },
    };
</script>

<style scoped lang="stylus">
    .rulesBox {
        display: flex;
        align-items center;
        flex-wrap: wrap;
    }

    .attrFrom {
        >>> .ivu-form-item {
            margin-bottom: 0px !important;
        }
    }
    .sub{
        text-align right
        margin 20px 0 0 20px
    }
</style>